package com.yindian.cos.easy.security.authentication;

import lombok.Data;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 拦截器链
 *
 * @author zhangchuanhao
 * @create 2018/11/18
 */
@Data
@Log4j2
public class AuthenticationChain {

    /**
     * spring中所有的AbstractAuthentication
     */
    private final Map<String, AbstractAuthentication> authenticationMap;

    /**
     * 排序后的调用链
     */
    private final List<AbstractAuthentication> authentications;

    public AuthenticationChain(Map<String, AbstractAuthentication> authenticationMap) {
        this.authenticationMap = authenticationMap;
        authentications = sort(authenticationMap);
    }

    /**
     * 排序
     *
     * @return
     */
    public List<AbstractAuthentication> sort(Map<String, AbstractAuthentication> authenticationMap) {
        List<AbstractAuthentication> abstractAuthentications = new ArrayList<>(authenticationMap.size());
        authenticationMap.forEach((k, v) -> {
            abstractAuthentications.add(v);
        });
        if (!abstractAuthentications.isEmpty()) {
            Collections.sort(abstractAuthentications, (a, b) -> {
                if (a.order() >= b.order()) {
                    return 1;
                }
                return -1;
            });
        }
        log.debug("easy security 拦截器：{}", abstractAuthentications);
        return abstractAuthentications;
    }
}
